const { $Toast } = require('../iview/base/index');
const Tools = require('./Tools');

class NetWork {
	constructor(baseLine){
		this.baseLine = baseLine;
	}

  _request(obj, toast = '', success = () =>  {}, fail = () => {}, complete = () => {}) {

		if(toast){
			$Toast({
	            content: '正在' + toast + '...',
	            type: 'loading'
	        });
		}

		let data = {
			url : '',
			data : {},
			header : {
				'content-type' : 'application/json'
			},
			method : 'GET',
			dataType : 'json',
			responseType : 'text',
		}
		
		let newData = Object.assign(data, obj);

		if(data.method.toUpperCase() == 'POST'){
      newData.header['content-type'] = 'application/json';
		}

		let _that = this;
    newData.url = _that.baseLine + newData.url;
		newData.success = function (res){
      
			// if(!Tools.isLogin(res.data, false)){
			// 	wx.redirectTo({
			// 		url: '/pages/login/index'
			// 	})
			// 	return false;
			// }

			if(toast) $Toast.hide();
      if (res.data.error_code == 0 ){
            if(toast){
              $Toast({
                      content: toast + '成功',
                      type: 'success'
                  });
            }
				
            // if(typeof res.data == 'string'){
            // 	let a = res.data.replace(/:\\/, ':/');
            // 	//console.log(a)
            // 	/**/
            // 	res.data = JSON.parse(a)
            //
            // }
        success(res);
      } else{
				fail(res)
				
			}
		}

		newData.fail = function (){

			if(toast){
				$Toast.hide();
				$Toast({
		            content: toast + '失败',
		            type: 'error'
		        });
			}

			fail();
		}

		newData.complete = function (){
			complete();
		}

		wx.request(newData);

	}

	_upload(obj = {}, success = ()=>{}, fail = () => {}, complete = () => {}){
		let bool = false;
		let message = '';
		let data = {
			url : '',
			formData : {},
			filePath : '',
			name : '',
			header : {
				'content-type' : 'multipart/form-data'
			},
			method : 'POST',
		}

   

    

		
		let newData = Object.assign(data, obj);
  

  
		newData.url = this.baseLine + newData.url;
  
		if(newData.filePath == ''){
			bool = true
			message = '请填写上传图片路径'
		}else if(newData.name == ''){
			bool = true
			message = '请填写Key值'
		}


		newData.success = function (res, statusCode){
 
      console.log(res);
			var _data = JSON.parse(res.data);
     
      if (_data.code == 200){
        success(res, statusCode)
			}else{
				$Toast({
					content: _data.message,
					type: 'error'
				})
			}
		}

		newData.fail = function (){
			fail()
		}

		newData.complete = function (){
			complete()
		}

		return wx.uploadFile(newData)

	}
}


export default NetWork;